<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-row >
          <el-form-item label="MCU类型">
            <el-select v-model="queryParams.mcuModel" clearable placeholder="请选择MCU类型" style="width:300px">
              <el-option
                v-for="item in mcuSysTypeListData"
                :key="item.id"
                :label="item.model+'（'+item.name+'）'"
                :value="item.model">
                <span style="float: left">{{ item.model }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="型号" prop="model">
            <el-input v-model="queryParams.model" placeholder="请输入型号" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
      </el-row>
      <el-form-item label="厂商" prop="vendor">
        <el-input v-model="queryParams.vendor" placeholder="请输入厂商" clearable @keyup.enter.native="handleQuery" style="width:300px"/>
      </el-form-item>

      <el-form-item label="版本" prop="edition">
        <el-input v-model="queryParams.edition" placeholder="请输入版本" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['hardware:sensor-sys-type:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['hardware:sensor-sys-type:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">

      <!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="关联MCU" align="center" prop="mcuModel"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="型号" align="center" prop="model"/>
      <el-table-column label="厂商" align="center" prop="vendor"/>
      <el-table-column label="版本" align="center" prop="edition"/>
      <el-table-column label="说明" align="center" prop="specification"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['hardware:sensor-sys-type:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['hardware:sensor-sys-type:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <!--    <el-dialog :title="title" :visible.sync="open" custom-class="sitesFormDialog" append-to-body>-->

    <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-row :gutter="100">
          <el-col :span="24">
            <el-form-item label="MCU类型" prop="mcuModel">
              <el-select v-model="form.mcuModel" placeholder="请选择MCU类型" style="width:41.8%">
                <el-option
                  v-for="item in mcuSysTypeListData"
                  :key="item.id"
                  :label="item.model+'（'+item.name+'）'"
                  :value="item.model">
                  <span style="float: left">{{ item.model }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="100">
          <el-col :span="12">
            <el-form-item label="厂商" prop="vendor">
              <el-input v-model="form.vendor" placeholder="请输入厂商"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本" prop="edition">
              <el-input v-model="form.edition" placeholder="请输入版本"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="传感器属性" prop="attributeMetadata">
              <span style="color: #999092;font-size: 8px;">*传感器属性的排序号只会影响显示的排序</span>
              <el-button type="warning" plain round @click="addAttributeMetadataItem">添加传感器属性</el-button>
              <el-button type="text" size="small" icon="el-icon-view" @click="handlePreview">显示预览</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-table v-if="attributeMetadataLength != 0" border ref="dragTable" :data="form.attributeMetadata"
                    :max-height="tableHeight">
            <el-table-column label="显示名称" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="代码字段" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.code"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="字段排序" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.sorts" size="mini" controls-position="right"
                                 :min="1"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="是否显示" min-width="7%">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.isShow" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>

            <el-table-column label="显示类型" min-width="10%">
              <template slot-scope="scope">
                <el-select v-model="scope.row.htmlType">
                  <el-option label="文本框" value="input"/>
                  <el-option label="下拉框" value="select"/>
                  <el-option label="计数器" value="inputNumber"/>
                  <el-option label="开关" value="switch"/>
                  <el-option label="日期控件" value="datetime"/>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="placeholder占位符" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.placeholder"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="显示类型为下拉框时的值" min-width="20%">
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="tag in scope.row.dynamicTags"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag,scope.$index)">
                  {{ tag }}
                </el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput{{scope.$index}}"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.$index)"
                          @blur="handleInputConfirm(scope.$index)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.$index)">+ 添加下拉框的值
                </el-button>
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="5%">
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" circle
                           @click.prevent="removeAttributeMetadataItem(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="13">
            <el-form-item label="上报数据值对应的属性" prop="valueMetadata">
              <span style="color: #999092;font-size: 8px;">*上报的数据中除非是有明显的key-value来对应所添加的的"代码字段"值，否则会根据排序号来对应</span>
              <el-button type="warning" plain round @click="addValueMetadataItem">添加值对应的属性</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-table v-if="valueMetadataLength != 0" border ref="dragTable" :data="form.valueMetadata"
                    :max-height="tableHeight">
            <el-table-column label="显示名称" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="代码字段" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.code"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="字段排序" min-width="10%" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.sorts" size="mini" controls-position="right"
                                 :min="1"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="是否显示" min-width="7%">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.isShow" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>

            <el-table-column label="操作" min-width="5%">
              <template slot-scope="scope">
                <el-button type="danger" icon="el-icon-delete" circle
                           @click.prevent="removeValueMetadataItem(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="说明" prop="specification">
              <el-input v-model="form.specification" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>


      <!--预览-->
      <el-dialog custom-class="sitesFormDialog" :visible.sync="innerVisible" append-to-body>
        <el-form ref="innerData" :model="formInner" label-width="140px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联的MCU" prop="mcuModel">
                <el-select v-model="formInner.mcuModel" placeholder="请选择关联的MCU">
                  <el-option
                    v-for="item in mcuSysTypeListData"
                    :key="item.id"
                    :label="item.model"
                    :value="item.model">
                    <span style="float: left">{{ item.model }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="通道号" prop="mcuChannel">
                <el-input placeholder="通道号为关联的MCU通道号"/>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联的传感器" prop="mcuTenantResourceId">
                <el-select v-model="formInner.model" placeholder="请选择关联的传感器">
                  <el-option :label="formInner.name" :value="formInner.model"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <div v-for="item in innerAttributeMetadata" :key="item.code">
              <el-col :span="12">
                <el-form-item v-if="item.isShow" :label="item.name" :prop="item.code">
                  <el-input v-if="item.htmlType =='input'" v-model="item.inputValue" :placeholder="item.placeholder"/>

                  <el-select v-if="item.htmlType =='select'" v-model="item.inputValue" :placeholder="item.placeholder">
                    <el-option v-for="it in item.dynamicTags" :key="it" :label="it" :value="it"></el-option>
                  </el-select>

                  <el-switch v-if="item.htmlType =='switch'" v-model="item.inputValue" active-color="#13ce66"
                             inactive-color="#ff4949"></el-switch>

                  <el-date-picker v-if="item.htmlType =='datetime'" v-model="item.inputValue" type="datetime"
                                  :placeholder="item.placeholder"></el-date-picker>

                  <el-input-number v-if="item.htmlType =='inputNumber'" v-model="item.inputValue"
                                   :placeholder="item.placeholder" size="mini" controls-position="right"
                                   :min="1"></el-input-number>

                </el-form-item>
              </el-col>
            </div>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="13">
              <el-form-item label="预警数据" prop="metadata">
                <el-button type="warning" plain round>新增预警</el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="innerVisibleClose">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  createSensorSysType,
  deleteSensorSysType,
  exportSensorSysTypeExcel,
  getSensorSysType,
  getSensorSysTypePage,
  updateSensorSysType
} from "@/api/hardware/sensorSysType";
import {getMcuSysTypeList} from "@/api/hardware/mcuSysType";

export default {
  name: "SensorSysType",
  components: {},
  data() {
    return {
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传感器系统分类列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        mcuModel: null,
        model: null,
        name: null,
        specification: null,
        type: null,
        vendor: null,
        edition: null,
      },
      // 表单参数
      form: {
        valueMetadata: [],
        attributeMetadata: []
      },
      formInner: {},
      innerAttributeMetadata: [],
      // 表单校验
      rules: {
        mcuModel: [{required: true, message: "传感器类型不能为空", trigger: "blur"}],
        model: [{required: true, message: "型号不能为空", trigger: "blur"}],
        name: [{required: true, message: "名称不能为空", trigger: "blur"}],
        agreementNo: [{required: true, message: "协议类型不能为空", trigger: "blur"}],
      },
      mcuSysTypeListData: [],
      attributeMetadataLength: 0,
      valueMetadataLength: 0,
      innerVisible: false
    };
  },
  created() {
    this.getList();
    this.queryMcuSysTypeList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getSensorSysTypePage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    queryMcuSysTypeList() {
      getMcuSysTypeList({}).then(response => {
        this.mcuSysTypeListData = response.data;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        model: undefined,
        name: undefined,
        specification: undefined,
        mcuModel: undefined,
        vendor: undefined,
        edition: undefined,
        valueMetadata: [],
        attributeMetadata: []

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.attributeMetadataLength = 0;
      this.valueMetadataLength = 0;
      this.reset();
      this.open = true;
      this.title = "添加传感器系统分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSensorSysType(id).then(response => {
        this.form = response.data;
        this.attributeMetadataLength = this.form.attributeMetadata.length;
        this.valueMetadataLength = this.form.valueMetadata.length;
        this.open = true;
        this.title = "修改传感器系统分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateSensorSysType(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSensorSysType(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除传感器系统分类编号为"' + id + '"的数据项?').then(function () {
        return deleteSensorSysType(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有传感器系统分类数据项?').then(() => {
        this.exportLoading = true;
        return exportSensorSysTypeExcel(params);
      }).then(response => {
        this.$download.excel(response, '传感器系统分类.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    addAttributeMetadataItem() {
      this.form.attributeMetadata.push(
        {
          name: undefined,
          code: undefined,
          isShow: true,
          sorts: (this.attributeMetadataLength + 1),
          htmlType: "input",
          placeholder: '',
          dynamicTags: [],
          inputVisible: false,
          inputValue: ''
        });
      this.attributeMetadataLength = this.form.attributeMetadata.length
    },
    removeAttributeMetadataItem(item) {
      let index = this.form.attributeMetadata.indexOf(item)
      if (index !== -1) {
        this.form.attributeMetadata.splice(index, 1)
      }
    },
    addValueMetadataItem() {
      this.form.valueMetadata.push({
        name: undefined,
        code: undefined,
        isShow: true,
        sorts: (this.form.valueMetadata.length + 1)
      });
      this.valueMetadataLength = this.form.valueMetadata.length
    },
    removeValueMetadataItem(item) {
      let index = this.form.valueMetadata.indexOf(item)
      if (index !== -1) {
        this.form.valueMetadata.splice(index, 1)
      }
    },
    handleClose(tag, index) {
      this.form.attributeMetadata[index].dynamicTags.splice(this.form.attributeMetadata[index].dynamicTags.indexOf(tag), 1);
    },

    showInput(index) {
      if (!this.form.attributeMetadata) {
        this.form.attributeMetadata = [];
      }

      if (!this.form.attributeMetadata[index].dynamicTags) {
        this.form.attributeMetadata[index].dynamicTags = [];
      }
      this.form.attributeMetadata[index].inputVisible = true;
    },

    handleInputConfirm(index) {
      let inputValue = this.form.attributeMetadata[index].inputValue;
      if (inputValue) {
        this.form.attributeMetadata[index].dynamicTags.push(inputValue);
      }
      this.form.attributeMetadata[index].inputVisible = false;
      this.form.attributeMetadata[index].inputValue = '';
    },
    handlePreview() {
      this.innerVisible = true;
      this.formInner = this.form;
      this.innerAttributeMetadata = this.form.attributeMetadata.sort(this.compare("sorts"));
      this.innerAttributeMetadata.forEach(it => {
        if (it.htmlType === 'switch') {
          if (it.inputValue === 'true') {
            it.inputValue = true
          } else if (it.inputValue === 'false') {
            it.inputValue = false
          } else {
            it.inputValue = true
          }
        }
      })
    },
    innerVisibleClose() {
      this.innerVisible = false;
    },
    compare(property) {
      return function (obj1, obj2) {
        let value1 = obj1[property];
        let value2 = obj2[property];
        return value1 - value2;     // 升序
      }
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-input-number--mini {
  width: 90px;
  line-height: 26px;
}

.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-top: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  margin-top: 10px;
  vertical-align: bottom;
}
</style>
